import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components'
import {AtForm, AtInput, AtButton} from 'taro-ui'
import {http} from '../../utils/http'
import {AlipayType} from '../../utils/server.interface'
import {GET_ALIPAY, UPDATE_ALIPAY} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './alipay.scss'

interface PageType {
  alipay_no: string
  true_name: string
  submiting: boolean
}

export default class Alipay extends Component {
  state: PageType = {
    alipay_no: '',
    true_name: '',
    submiting: false,
  }

  async componentDidShow() {
    vcmonitor(this)
    this.initData()
  }

  async initData() {
    const alipay = await http.get<AlipayType>(GET_ALIPAY, {})
    if (alipay) {
      this.setState({alipay_no: alipay.userAlipay.alipay_no || '', true_name: alipay.userAlipay.true_name || ''})
    }
  }

  async submitFunc() {
    if (!this.state.submiting) {
      this.setState({submiting: true})
      Taro.showLoading({title: '提交中...'})
      const {alipay_no, true_name} = this.state
      const ret = await http.postCondition<boolean>(UPDATE_ALIPAY, {alipay_no, true_name})
      if (ret.isOk) {
        Taro.showToast({title: '保存成功'})
        await this.initData()
        Taro.navigateBack({
          delta: 1
        })
      } else {
        if (ret.msg) {
          Taro.showToast({title: ret.msg, icon: 'none'})
        }
      }
      const timer = setTimeout(() => {
        Taro.hideLoading()
        this.setState({submiting: false})
        clearTimeout(timer)
      }, 100)
    }
  }

  render() {
    const {alipay_no, true_name, submiting} = this.state
    return (
      <View className='alipay-root'>
        <GzhAuth />
        <View className='title'>绑定支付宝账号</View>
        <AtForm className='form'>
          <AtInput type='text' value={alipay_no} name='alipay_no' title='支付宝账号' placeholder='请填写支付宝账号'
            onChange={(res) => {
                     this.setState({
                       alipay_no: res
                     })
                   }}
          />
          <AtInput type='text' value={true_name} name='true_name' title='真实姓名' placeholder='请填写支付宝账号关联真实姓名'
            onChange={(res) => {
                     this.setState({
                       true_name: res
                     })
                     return res
                   }}
          />
        </AtForm>
        <View className='btn-box'>
          <AtButton type='primary' loading={submiting} disabled={submiting}
            onClick={this.submitFunc.bind(this)}
          >保存</AtButton>
        </View>
      </View>
    )
  }
}

